package gatewayRouter

import (
	"encoding/json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedis"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
)

type redisConfig struct {
	Prefix string
}

func (e *redisConfig) getConfig() ([]*RouterVO, error) {
	// 获得所有的key
	keys, err := commRedis.Client.Keys(e.Prefix + ":*").Result()
	if err != nil {
		return nil, err
	}

	// 逐个key进行反系列化
	voList := make([]*RouterVO, 0)
	for _, key := range keys {
		jsn, err := commRedis.Client.Get(key).Result()
		if err != nil {
			continue
		}
		if jsn == "" {
			continue
		}

		data := Json.BuildMapByJson(jsn)
		if len(data) == 0 {

		}

		var vo RouterVO
		err = json.Unmarshal([]byte(jsn), &vo)
		if err != nil {
			continue
		}

		voList = append(voList, &vo)
	}

	return voList, nil
}

func (e *redisConfig) setConfig(vo *RouterVO) error {
	// 获得所有的key
	_, err := commRedis.Client.Set(e.Prefix+":"+vo.Id, Json.BuildJson(vo), -1).Result()
	if err != nil {
		return err
	}

	return nil
}

func (e *redisConfig) delConfig(id string) error {
	// 获得所有的key
	keys, err := commRedis.Client.Keys(e.Prefix + ":" + id).Result()
	if err != nil {
		return err
	}

	// 逐个key进行删除
	for _, key := range keys {
		commRedis.Client.Del(key).Result()
	}

	return nil
}
